package com.starsoft.smdc.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.starsoft.frame.core.orm.PageObject;
import com.starsoft.frame.core.web.WebUtil;
import com.starsoft.frame.util.MapUtil;
import com.starsoft.frame.util.StringUtil;
import com.starsoft.smdc.bean.SmdcSecurity;
import com.starsoft.smdc.crawler.SmdcUpdateService;
import com.starsoft.smdc.service.SecurityService;

@RestController
@RequestMapping(value = "/smdc/security")
public class SecurityController {

	@Autowired
	SecurityService securityService;
	
	@Autowired
	SmdcUpdateService updateService;
	
	@RequestMapping(value="/page")
	public Map<String, Object> pageQuery(HttpServletRequest request){
		PageObject po = WebUtil.getPageObject(request);
		String secId = request.getParameter("secId");
		String exchange = request.getParameter("exchange");
		String secType = request.getParameter("secType");
		String fundCategory = request.getParameter("fundCategory");
		return securityService.pageQuery(po, secId, exchange, secType, fundCategory);
	}
	
	@RequestMapping(value="/comgridpage")
	public Map<String, Object> comgridPageQuery(HttpServletRequest request){
		PageObject po = WebUtil.getPageObject(request);
		String key = request.getParameter("q");
		if(key!=null){
			key = key.trim();
		}
		String secTypeStr = null;
		String billType = request.getParameter("billType");
		if(!StringUtil.isEmpty(billType)){
			secTypeStr = billType.replace("sell", "").replace("buy", "").replace("div", "");
		}
		return securityService.pageQuery(po, key, null, secTypeStr, null);
	}
	
	@RequestMapping(value="/delete")
	public Map<String, Object> delete(HttpServletRequest request){
		String secId = request.getParameter("secId");
		securityService.deleteWithMarket(secId);
		return WebUtil.sucesseModel(null);
	}
	
	@RequestMapping(value="/save")
	public Map<String, Object> save(HttpServletRequest request, SmdcSecurity security){
		String secId = security.getSecId();
		SmdcSecurity securityDb = securityService.get(secId);
		String editType = request.getParameter("editType");
		if(securityDb!=null && !"edit".equals(editType)){
			return WebUtil.errorModel(secId +"已经存在只能编辑");
		}
		if(securityDb!=null){
			MapUtil.updateBean(securityDb, MapUtil.toMap(security));
		} else {
			securityDb = security;
		}
		securityService.saveOrUpdate(securityDb);
		return WebUtil.sucesseModel("保存成功");
	}
	
}
